package com.xoa.util.cms.directive;

import com.xoa.dao.cms.SiteMapper;
import com.xoa.model.cms.Site;
import com.xoa.model.cms.SiteExample;
import com.xoa.util.common.StringUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 张勇 on 2018/3/14.
 */
public class CMSSiteDirective implements TemplateDirectiveModel {

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        //获取参数中的站点id
        String siteIdFromParam = StringUtils.getString(map.get("id"));
        //获取env当中的站点id
        int siteId = StringUtils.getInteger(environment.getCustomAttribute("SITE_ID"),0);
        //获取栏目id
        int curChannelId = StringUtils.getInteger(environment.getCustomAttribute("CHANNEL_ID"),0);

        //获取mapper
        SiteMapper siteMapper = (SiteMapper) environment.getCustomAttribute("siteMapper");

        //获取上层的参数
        Object loopObj = environment.getCustomAttribute("loopObj");

        Writer w = environment.getOut();

        Site site = null;
        if(!"".equals(siteIdFromParam)){
            SiteExample example = new SiteExample();
            SiteExample.Criteria criteria = example.createCriteria();
            criteria.andPortalMarkEqualTo(siteIdFromParam);
            List<Site> sites = siteMapper.selectByExample(example);
            if(sites != null && sites.size()>0){
                site = sites.get(0);
            }
        }else{
            site = siteMapper.selectByPrimaryKey(siteId);
        }
        if(site==null){
            return ;
        }
        Map param = new HashMap();
        param.put("siteId",site.getPortalId());
        param.put("siteMark",site.getPortalMark());
        param.put("siteName",site.getPortalName());
        param.put("siteNo",site.getSortNo());
        param.put("sitePath",site.getPath());

        //覆盖当前标签的变量，传到下一层
        environment.setCustomAttribute("loopObj",param);
        if(templateDirectiveBody!=null){
            templateDirectiveBody.render(w);
        }

        //还原上一层的变量
        environment.setCustomAttribute("loopObj",loopObj);
    }

}
